package com.qf.smartplatform.service.impl;

import com.qf.smartplatform.cache.CategoryCache;
import com.qf.smartplatform.constans.ResultCode;
import com.qf.smartplatform.event.CategoryChangeEnent;
import com.qf.smartplatform.exceptions.DeleteDataException;
import com.qf.smartplatform.exceptions.FindDataException;
import com.qf.smartplatform.exceptions.UnLoginException;
import com.qf.smartplatform.exceptions.UpdateDateException;
import com.qf.smartplatform.mapper.CategoryMapper;
import com.qf.smartplatform.pojo.BaseUser;
import com.qf.smartplatform.pojo.SysCategory;
import com.qf.smartplatform.pojo.SysUserInfo;
import com.qf.smartplatform.service.CategoryService;
import com.qf.smartplatform.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    private ApplicationContext context;
    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    private CategoryCache categoryCache;
@Autowired
    public void setCategoryCache(CategoryCache categoryCache) {
        this.categoryCache = categoryCache;
    }

    private CategoryMapper categoryMapper;
    @Autowired
    public void setCategoryMapper(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    @Override
    public void addCategory(SysCategory sysCategory) {

        BaseUser loginUser = SecurityUtils.getUser();

        if (loginUser==null) {
            throw new UnLoginException("未登录，请先登录", ResultCode.NOT_LOGIN);
        }
        sysCategory.setCreateBy(loginUser.getUsername());
        SysCategory sysCategoryByName = categoryMapper.findByName(sysCategory.getCategoryName());
//        Assert.isNull(sysCategoryByName,()->{
//            if (sysCategoryByName.getStatus()==0){
//                
//            }
//            throw new FindDataException("数据已存在",ResultCode.USERNAME_ALREADY_EXIST);
//        });
        if (sysCategoryByName!=null && sysCategoryByName.getStatus()==1){
            throw new FindDataException("数据已存在",ResultCode.USERNAME_ALREADY_EXIST);
        } else if (sysCategoryByName!=null && sysCategoryByName.getStatus()==0) {
            sysCategoryByName.setCategoryName(sysCategoryByName.getCategoryName()+"teshuzifu");
            sysCategoryByName.setCreateBy(loginUser.getUsername());
            categoryMapper.updateCategory(sysCategoryByName);
        }
        categoryMapper.addCategory(sysCategory);
        context.publishEvent(new CategoryChangeEnent());
    }
    public List<SysCategory> findAllCategories(){
        List<SysCategory> categoryList = categoryCache.getList();
        return categoryList.stream().filter(sysCategory -> sysCategory.getStatus()==1).collect(Collectors.toList());
    }

    @Override
    public SysCategory findCategoryById(Long cId) {

//        List<SysCategory> categoryList = categoryCache.getCategoryList();
//        for (SysCategory sysCategory : categoryList) {
//            if (sysCategory.getCId().equals(cId)){
//                return sysCategory;
//            }
//        }



        SysCategory sysCategory = categoryCache.getById(cId);
        Assert.notNull(sysCategory,()->{
            throw  new FindDataException("数据不存在",ResultCode.DATA_NOT_EXIST);
        });
    return categoryCache.getById(cId);
    }

    @Override
    public String deleteCategoryById(Long cId) {
        int result=categoryMapper.deleteCategoryById(cId);
        context.publishEvent(new CategoryChangeEnent());
         if (result==0){
             throw new DeleteDataException("删除失败",ResultCode.DELETE_FAIL);
         }
             return "删除成功";
    }

    @Override
    public String updateCategory(SysCategory sysCategory) {
        //判断表中是否有符合更新条件的数据
        SysCategory category=categoryMapper.findByCid(sysCategory.getCId());
        Assert.notNull(category,()->{
            throw new FindDataException("没有cId符合条件的数据",ResultCode.DATA_NOT_EXIST);
        });
        //判断是否已经登录
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        SysUserInfo user = (SysUserInfo) request.getSession().getAttribute("user");
        Assert.notNull(user,()->{
            throw new UnLoginException("未登录，请先登录",ResultCode.NOT_LOGIN);
        });

        sysCategory.setUpdateBy(user.getUsername());
        sysCategory.setUpdateTime(new Date());
        int result=categoryMapper.updateCategory(sysCategory);
        context.publishEvent(new CategoryChangeEnent());

        if (result==0){
            throw new UpdateDateException("更新未成功",ResultCode.UPDATE_FAIL);
        }
        return "更新成功";
    }

}
